use std::env;
use std::fs;
use std::io;
use std::path::Path;

// 获取文件地址
fn get_file_absolute_path() -> String {
    let root_path = env::current_dir().unwrap();
    let path = Path::new(&root_path).join("storage/baidu.html");
    return path.to_str().unwrap().to_string();
}

// 写入文件
fn write_string(file_path: &str, content: &str) -> io::Result<()> {
    fs::write(file_path, content)?;
    Ok(())
}

// 请求接口
async fn request() -> Result<String, reqwest::Error> {
    let body = reqwest::get("https://www.baidu.com").await?.text().await?;
    Ok(body)
}

#[tokio::main]
async fn main() {
    match request().await {
        Ok(res) => {
            // 请求成功写入文件
            let path = get_file_absolute_path();
            match write_string(&path, res.to_string().as_str()) {
                Ok(_) => println!("写入成功: {}", path),
                Err(e) => println!("写入失败, {}", e),
            }
        }
        Err(e) => println!("请求失败, {}", e),
    };
}
